package com.songcha.sakura.util

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.Build
import com.songcha.library_database_sakura.greendao.GreenDaoManager
import com.songcha.library_database_sakura.greendao.VideoPlayProgressBean
import com.songcha.library_database_sakura.greendao.VideoPlayProgressBeanDao

class VideoUtil {
    companion object{
        @JvmStatic
        fun readPlayHistoryProgress(name:String):VideoPlayProgressBean?{
            val vpd= GreenDaoManager.getInstance().videoPlayProgressDao

            if(name.isNotEmpty()){
                try{
                    val qb=vpd.queryBuilder()
                    qb.where(VideoPlayProgressBeanDao.Properties.Name.eq(name))
                    val list=qb.list()
                    if(list.size>0){
                        //val position=list[0].position
                        //return position
                        return list[0]
                    }
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
            return null

        }

        @JvmStatic
        fun savePlayHistoryProgress(name:String,position:Int,duration:Int){
            val vpd= GreenDaoManager.getInstance().videoPlayProgressDao

            if(name.isNotEmpty()){
                val bean= VideoPlayProgressBean()
                bean.name=name
                bean.position=position
                bean.duration=duration
                try{
                    vpd.insertOrReplace(bean)
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }

        //获取视频指定帧,仅支持mp4

        @JvmStatic
        fun getVideoFrame(path:String,index:Int): Bitmap?{
            val mmr= MediaMetadataRetriever()//实例化MediaMetadataRetriever对象
            mmr.setDataSource(path)
            var bitmap:Bitmap?=null
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){
                bitmap = mmr.getFrameAtIndex(index)
            }else{
                bitmap = mmr.getFrameAtTime(0)
            }
            mmr.release() //释放MediaMetadataRetriever对象
            return bitmap
        }

    }
}